#include "vzLibuv.h"
#include "configParser.h"
#include "CxlUtil.h"
#include <stdlib.h>

static VzLibuvStruct *privateVzLibuvStruct;
static VzAppStruct *privateVzAppStruct;

void setPrivateVzlibuvStruct(VzLibuvStruct *vzLibStruct)
{
    privateVzLibuvStruct = vzLibStruct;
    privateVzAppStruct = container_of(vzLibStruct, VzAppStruct, uv);
}

VzAppStruct *getVzAppPtrFromUvConnect(uv_connect_t *client)
{
    VzLibuvStruct *vzLibuvStruct = container_of(client, VzLibuvStruct, client);
    VzAppStruct *vzAppStruct = container_of(vzLibuvStruct, VzAppStruct, uv);
    return vzAppStruct;
}

VzAppStruct *getVzAppPtrFromUvStream(uv_stream_t *stream)
{
    uv_connect_t *connect = container_of(stream, uv_connect_t, handle);
    return getVzAppPtrFromUvConnect(connect);
}

VzAppStruct *getVzAppPtrFromUvTimmerInterval(uv_timer_t *timmer)
{
    VzLibuvStruct *vzLibuvStruct = container_of(timmer, VzLibuvStruct, vzReq);
    VzAppStruct *vzAppStruct = container_of(vzLibuvStruct, VzAppStruct, uv);
    return vzAppStruct;
}

VzAppStruct *getVzAppPtrFromUvTimmerSetTimeOut(uv_timer_t *timmer)
{
    VzLibuvStruct *vzLibuvStruct = container_of(timmer, VzLibuvStruct, mainWorkSetTimeOut);
    VzAppStruct *vzAppStruct = container_of(vzLibuvStruct, VzAppStruct, uv);
    return vzAppStruct;
}

void vzInterval(void *cb, uint16_t time)
{
    uv_timer_start(&privateVzLibuvStruct->vzReq, cb, 0, time);
}

void vzClearInterval()
{
    uv_timer_stop(&privateVzLibuvStruct->vzReq);
}

void vzConnect(uv_connect_cb cb)
{
    uv_loop_t *loop = getLoop();
    uv_tcp_init(loop, &privateVzLibuvStruct->vz_socket);

    struct sockaddr_in dest;
    uv_ip4_addr(privateVzAppStruct->vzCamIp, privateVzAppStruct->vzCamPort, &dest);

    uv_tcp_connect(&privateVzLibuvStruct->client, &privateVzLibuvStruct->vz_socket, (const struct sockaddr *)&dest, cb);
}

// uv_connect_t *getVzClientConnect()
// {
//     return &privateVzLibuvStruct->client;
// }

void vzSetTimeout(void *cb, uint16_t time)
{
    if (uv_timer_get_due_in(&privateVzLibuvStruct->mainWorkSetTimeOut) > 0)
    {
        LOG_DEBUG("相机timeOut计时器仍在计时中，直接返回");
        return;
    }
    uv_timer_start(&privateVzLibuvStruct->mainWorkSetTimeOut, cb, time, 0);
}